package com.example.mardan.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mardan.entity.BookEntity;
import com.example.mardan.views.DetailsActivity;
import com.example.read.R;
import com.google.gson.Gson;

import java.util.List;

public class BooksAdapter extends RecyclerView.Adapter<BooksAdapter.ViewHolder>{
    private List<BookEntity.ResultData.BookData> bookDataList ;
    private Context context ;

    public BooksAdapter(List<BookEntity.ResultData.BookData> bookDataList, Context context) {
        this.bookDataList = bookDataList;
        this.context = context;
    }

    public void updateAdapter(List<BookEntity.ResultData.BookData> list){
        bookDataList.clear();
        this.bookDataList = list ;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(context , R.layout.item_main , null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BookEntity.ResultData.BookData bookData = bookDataList.get(position);

        holder.textView.setText(bookData.getTitle());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context , DetailsActivity.class);
                Gson gson = new Gson() ;
                intent.putExtra("bookData",gson.toJson(bookData));
                context.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return bookDataList == null ? 0 : bookDataList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        private TextView textView ;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.item_main_type);
        }
    }
}
